package com.nineclock.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.system.dto.SysRegisterDTO;
import com.nineclock.system.dto.SysUserDTO;
import com.nineclock.system.mapper.SysUserMapper;
import com.nineclock.system.pojo.SysUser;
import com.nineclock.system.service.SmsService;
import com.nineclock.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    SmsService smsService;


    @Override
    public Integer queryUserForMobile(String mobile) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getMobile,mobile);
        Integer count = sysUserMapper.selectCount(wrapper);
        return count;
    }

    @Override
    public Long register(SysRegisterDTO sysRegisterDTO) {
        //参数校验
        if(sysRegisterDTO.getMobile() == null || sysRegisterDTO.getCheckcode()==null || sysRegisterDTO.getPassword() == null){
            throw new NcException(ResponseEnum.MESSAGE_PARAMS_LOST);
        }
        //校验验证码
        Boolean smsCode = smsService.verifySmsCode(sysRegisterDTO.getMobile(), SMSConstant.SMS_TYPE_REGISTER, sysRegisterDTO.getCheckcode());
        if (!smsCode){
            throw new NcException(ResponseEnum.CODE_IMAGE_ERROR);
        }
        //保存用户信息
        SysUser sysUser = new SysUser();
        sysUser.setMobile(sysRegisterDTO.getMobile());
        //对密码进行加密
        sysUser.setPassword(new BCryptPasswordEncoder().encode(sysRegisterDTO.getPassword()));
        sysUser.setCreateTime(new Date());
        sysUser.setStatus((short)1);
        sysUserMapper.insert(sysUser);

        return sysUser.getId();
    }

    @Override
    public SysUserDTO queryUser(String username) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername,username).or().eq(SysUser::getMobile,username);
        wrapper.eq(SysUser::getStatus,1);
        SysUser sysUser = sysUserMapper.selectOne(wrapper);
        if (sysUser !=null){
            SysUserDTO sysUserDTO = BeanHelper.copyProperties(sysUser, SysUserDTO.class);
            return sysUserDTO;
        }
        return null;
    }
}
